import java.lang.reflect.Array;
import java.util.Arrays;

public class Test17 {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        int[] Buy = new int[n];
        int[] Tradable = new int[n];
        int[] arr  = new int[n];
        int m = 0;
        Buy[0] = -prices[0];
        for (int i = 1; i < n; i++) {
            Buy[i] = Math.max(Tradable[i - 1] - prices[i], Buy[i - 1]);
            Tradable[i] = Math.max(Buy[i - 1] + prices[i], Tradable[i - 1]);
            if (Buy[i - 1] + prices[i] > Tradable[i - 1]) {
                arr[m++] = Tradable[i];
            }
        }
        Arrays.sort(arr,0,m);
        for (int i = m - 1; i > 0; i--) {
            arr[i] = arr[i] - arr[i - 1];

        }
        Arrays.sort(arr,0,m);
        return arr[m - 1] + arr[m - 2];
    }
    public static void main(String[] args) {
        int[] arr = {3,3,5,0,0,3,1,4};
        Test17 test17 = new Test17();
        System.out.println(test17.maxProfit(arr));

    }
}
